package com.zlp.config.restTemplate;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class RestTemplateLog implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) {
        String path = request.getURI().getPath();
        String header = String.valueOf(request.getHeaders());
        String param = new String(body, StandardCharsets.UTF_8);
        log.info("RestTemplate请求信息:【请求URL：{}，请求头：{}，请求参数：{}】", path, header, param);
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        String line = null;
        try (BufferedReader bufferedReader =
                     new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8))) {
            line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
        }
        int status = response.getStatusCode().value();
        String body = String.valueOf(inputStringBuilder).trim();
        log.info("RestTemplate响应信息:【状态码：{}，响应参数：{}】", status, body);
    }

}
